package concurrecy;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 睡眠
 */
class SleepTask implements Runnable {
    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(100);
        } catch (InterruptedException e) {
            System.out.println("Interrupted on sleep");
        }
        System.out.println("Exit from sleep task");
    }
}

class IOTask implements Runnable {
    @Override
    public void run() {
        try {
            System.in.read();
        } catch (IOException e) {
            System.out.println("read error");
        }
        System.out.println("Exit from read");
    }
}

class SyncTask implements Runnable {

    private synchronized void f() {
        while(true)
            Thread.yield();
    }

    public SyncTask() {
        new Thread(() -> {
            try {
                f();
            } catch (Exception e) {
                System.out.println("invoke f() error");
            }
            System.out.println("Exit from Thread f()");
        }).start();
    }

    @Override
    public void run() {
        try {
            TimeUnit.MILLISECONDS.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            f();
        } catch (Exception e) {
            System.out.println("invoke f() error");
        }
        System.out.println("Exit from run f()");
    }
}

/**
 * 终止一个线程
 */
public class TerminateDemo {

    static ExecutorService service = Executors.newCachedThreadPool();

    static void test(Runnable runnable) {
        Future<?> future = service.submit(runnable);
        System.out.println("cancel " + runnable.getClass().getSimpleName());
        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        future.cancel(true);
    }

    public static void main(String[] args) {
        test(new SleepTask());
        test(new IOTask());
        test(new SyncTask());

        service.shutdown();
    }
}
